import axios from 'axios';
import {Message, message} from 'element-ui';
import router from '../router';

// 封装网络响应请求
// axios网络拦截器，拦截response
axios.interceptors.response.use(success => {
    // 如果success.status不为空 并且 status为200(请求的返回码) ,success.data.status为后端json返回状态码
    if (success.status && success.status == 200 && success.data.status == 500) {
        Message.error({message: success.data.msg})
        return;
    }
    if (success.data.msg){
        Message.success({message: success.data.msg});
    }
    return success.data;
}, error => {
    console.log(error.response.status);
    console.log(error.response.status == 401);
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message: '服务器被吃了o(╯□╰)o'});
    } else if (error.response.status == 403) {
        Message.error({message: '权限不足，请联系管理员'});
    } else if (error.response.status == 401) {
        Message.error({message: '尚未登录，请登录!'});
        router.replace('/');
        console.log('跳转啊');
    } else {
        if (error.response.data.msg) {
            console.log('你怕是个傻子(⊙o⊙)哦');
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误 o(>﹏<)o'})
        }
    }
    return;
});

let base = '';

export const postKeyValueRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            console.log('我是拼接的请求字符串ret=>',ret);
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
};

// post请求
export const postRequest=(url, params)=>{
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params
    })
};

// put请求
export const putRequest=(url, params)=>{
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
};

// get请求
export const getRequest=(url, params)=>{
    return axios({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
};

// delete请求
export const deleteRequest=(url, params)=>{
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        data: params
    })
};
